// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.ServiceDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.Service;
import net.taviscaron.drivenotes.shared.service.ServiceService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service service impl
 * @author Andrei Senchuk
 */
public class ServiceServiceImpl implements ServiceService {
    private Validator<Service> serviceValidator;
    private ServiceDAO serviceDAO;

    @Required
    public void setServiceValidator(Validator<Service> serviceValidator) {
        this.serviceValidator = serviceValidator;
    }

    @Required
    public void setServiceDAO(ServiceDAO serviceDAO) {
        this.serviceDAO = serviceDAO;
    }

    @Transactional
    public List<Service> findServicesByCar(Car car) {
        List<Service> services = serviceDAO.findServicesByCar(car);
        for(int i = 0; i < services.size(); i++) {
            services.set(i, EntityUtils.createServiceValueObject(services.get(i)));
        }
        return services;
    }

    @Transactional
    public void saveService(Service service) throws InvalidEntityException {
        serviceValidator.validate(service);
        serviceDAO.save(service);
    }

    @Transactional
    public Service findById(Long id) {
        Service serviceObj = serviceDAO.findById(id);
        Service service = EntityUtils.createServiceValueObject(serviceObj);
        if(service != null) {
            Car car = EntityUtils.createCarValueObject(serviceObj.getCar());
            car.setOwner(EntityUtils.createUserValueObject(serviceObj.getCar().getOwner()));
            service.setCar(car);
        }
        return service;
    }

    @Transactional
    public void removeServiceById(Long id) {
        Service service = serviceDAO.findById(id);
        serviceDAO.remove(service);
    }
}
